package com.example.ywj.toutiao.fragments;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.ywj.toutiao.DetailActivity;
import com.example.ywj.toutiao.R;
import com.example.ywj.toutiao.bean.News;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.example.ywj.toutiao.utils.SearchItemAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SearchFragment extends Fragment implements AdapterView.OnItemClickListener {
    private static final String TAG = "SearchFragment";
    public View view;
    //是否可见
    public boolean isVisible = false;
    //是否初始化完成
    public boolean isInit = false;
    //是否已经加载过
    public boolean isLoadOver = false;
    public String title;
    private String baseUrl = Constant.BASEURL;
    public ListView listView;
    public LinearLayout linearLayout;
    public TextView noresult_layout_title;
    public EditText et;
    public List<News> newList = new ArrayList<>();
    public TextView search_text_result;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null){
            view = inflater.inflate(R.layout.search_result_layout, null);
            isInit = true;
            getTitle();
        }
        return view;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisible = isVisibleToUser;
        getTitle();
    }
    public void getTitle(){
        if (isInit && !isLoadOver && isVisible) {
            //TextView tv = view.findViewById(R.id.textView);
            isLoadOver = true;
            title = getArguments().getString("title");
            et = getActivity().findViewById(R.id.search_editView_result);
            search_text_result = getActivity().findViewById(R.id.search_text_result);
            final String content = et.getText().toString();
            //Log.i(TAG, "getTitle: "+title);
            //Log.i(TAG, "getTitle: "+content);
            //tv.setText(title);
            listView = view.findViewById(R.id.search_list);
            linearLayout = view.findViewById(R.id.noresult_layout);
            noresult_layout_title = view.findViewById(R.id.noresult_layout_title);
            search_text_result.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    getData(title,content);
                }
            });
            getData(title,content);
        }

    }
    public void getData(String title,String content){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.search(title,content);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                    //Log.i(TAG, "onResponse: "+json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                //Integer status = obj.get("status").getAsInt();
                if(code == 200 && obj.has("status") ){
                    //没有数据
                    Log.i(TAG, "onResponse: "+1);
                    listView.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.VISIBLE);
                    noresult_layout_title.setText("抱歉，未找到“"+et.getText().toString()+"”相关内容");
                }else if(code == 200 && obj.has("data")){
                    Log.i(TAG, "onResponse: "+2);
                    //有数据
                    JsonArray objArr = obj.getAsJsonArray("data");
                    Log.i(TAG, "onResponse: "+objArr);
                    Gson gson = new Gson();
                    newList = gson.fromJson(objArr,new TypeToken<ArrayList<News>>(){}.getType());
                    SearchItemAdapter searchItemAdapter = new SearchItemAdapter(newList);
                    listView.setAdapter(searchItemAdapter);
                    listView.setOnItemClickListener(SearchFragment.this);
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        Log.i(TAG, "onItemClick: "+position);
        bundle.putString("id",newList.get(position).get_id());
        Intent intent = new Intent(parent.getContext(),DetailActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
